//
//  SegmentedProgressBar.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/8/10.
//

import SwiftUI

/// 单段配置
struct SegmentConfig: Identifiable {
    let id = UUID()
    var color: Color
    var title: String
    var alignment: HorizontalAlignment   // .leading / .center / .trailing
}

/// 整个控件的配置
struct ProgressConfig {
    var segments: [SegmentConfig]        // mit4 段
    var gap: CGFloat                     // 两段之间的空白
    var barHeight: Double
}

/// 带指示器的 4 段进度条
struct SleepProgressBar: View {
    var progress: Double            // 0...1
    var config: ProgressConfig
    
    @State private var totalWidth: CGFloat = 0
    
    // MARK: - 几何计算
    /// 含 gap 的总宽
    private var fullWidth: CGFloat { totalWidth }
    
    /// 4 段彩色区域总宽（不含 gap）
    private var validWidth: CGFloat {
        fullWidth - CGFloat(config.segments.count - 1) * config.gap
    }
    
    /// 单段彩色宽
    private var segmentWidth: CGFloat { validWidth / CGFloat(config.segments.count) }
    
    /// 每段左端在屏幕上的 X 坐标（含 gap）
    private var segmentLeftXs: [CGFloat] {
        (0..<config.segments.count).map { idx in
            CGFloat(idx) * (segmentWidth + config.gap)
        }
    }
    
    /// 指示器中心 X：连续且精准落在每段右端
    private var indicatorCenterX: CGFloat {
        let c     = CGFloat(config.segments.count)          // 4
        let gaps  = (c - 1) * config.gap                    // 总 gap 宽度
        let segW  = (totalWidth - gaps) / c                 // 单段彩色宽
        
        /* 1. 把 0~1 映射到“彩色总长” */
        let raw   = CGFloat(progress) * (c * segW)
        
        /* 2. 计算落在哪一段（0…3）和段内比例 */
        let index = min(Int(raw / segW), Int(c) - 1)
        let ratio = (raw - CGFloat(index) * segW) / segW    // 0…1 在本段内
        
        /* 3. 坐标 = 段起点 + 段内比例 * 段宽 + 前面 gap 补偿 */
        let x = CGFloat(index) * (segW + config.gap) + ratio * segW
        if progress == 0.25 || progress == 0.5 || progress == 0.75 {
            return x - config.gap
        }
        return x
    }
        
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // 1. 轨道 + 指示器
            GeometryReader { geo in
                ZStack(alignment: .topLeading) {
                    // 背景（整根）
                    Rectangle()
                        .fill(.clear)
                        .frame(height: config.barHeight)
                        .cornerRadius(6)
                        .padding(.top, 4)
                    
                    // 4 段彩色
                    HStack(spacing: config.gap) {
                        ForEach(config.segments) { seg in
                            seg.color
                                .frame(width: max(segmentWidth, 1), height: config.barHeight)
                        }
                    }
                    .cornerRadius(6)
                    .padding(.top, 4)
                    
                    Image("progressIcon")
                        .shadow(radius: 2)
                        .frame(width: 8, height: 6)
                        .offset(x: indicatorCenterX - 4)
                        .animation(.easeInOut(duration: 0.2), value: progress)
                }
                .onAppear { totalWidth = geo.size.width }
                .onChange(of: geo.size.width) { totalWidth = $0 }
            }
            .frame(height: config.barHeight + 4)
            
            HStack(spacing: config.gap) {
                ForEach(Array(config.segments.enumerated()), id: \.element.id) { _, seg in
                    Text(seg.title)
                        .font(.system(size: 12, weight: .regular))
                        .foregroundColor(Color(hex: "#B2B2B2"))
                        .lineLimit(1)
                        .fixedSize(horizontal: true, vertical: false)
                        .frame(width: max(segmentWidth, 1),
                               alignment: Alignment(horizontal: seg.alignment, vertical: .center))
                }
            }
            .padding(.top, 12)
        }
    }
}

struct SleepProgressBar_Previews: PreviewProvider {
    static var previews: some View {
        VStack(spacing: 40) {
            let cfg = ProgressConfig(
                segments: [
                    .init(color: .green,  title: "阶段 1",      alignment: .leading),
                    .init(color: .blue,   title: "阶段 2",    alignment: .center),
                    .init(color: .orange, title: "阶段 3",  alignment: .center),
                    .init(color: .red,    title: "阶段 4", alignment: .trailing)
                ],
                gap: 2,
                barHeight: 10
            )
            
            SleepProgressBar(progress: 0.25, config: cfg)
            SleepProgressBar(progress: 0.5,  config: cfg)
            SleepProgressBar(progress: 0.75, config: cfg)
            SleepProgressBar(progress: 1.0,  config: cfg)
        }
        .padding()
    }
}
